﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using Autofac;
using Macaca.Core.Infrastructure;
using Unis.Framework.Core.Configuration;
using Unis.Framework.Core.Infrastructure.DependencyManagement;

namespace Unis.Framework.Core.Infrastructure
{
    public class UnisEngine : IEngine
    {
        #region Fields

        private ContainerManager _containerManager;

        #endregion

        #region Properties

        public ContainerManager ContainerManager
        {
            get { return _containerManager; }
        }

        #endregion

        #region Constructor
        /// <summary>
        /// Creates an instance of the content engine using default settings and configuration.
        /// </summary>
        public UnisEngine()
            : this(EventBroker.Instance, new ContainerConfigurer())
        {
        }

        public UnisEngine(EventBroker broker, ContainerConfigurer configurer)
        {
            var config = ConfigurationManager.GetSection("UnisConfig") as UnisConfig;
            InitializeContainer(configurer, broker, config);
        }

        #endregion


        private void RunStartupTasks()
        {
            var typeFinder = _containerManager.Resolve<ITypeFinder>();
            var startUpTaskTypes = typeFinder.FindClassesOfType<IStartupTask>();
            var startUpTasks = new List<IStartupTask>();
            foreach (var startUpTaskType in startUpTaskTypes)
                startUpTasks.Add((IStartupTask)Activator.CreateInstance(startUpTaskType));
            //sort
            startUpTasks = startUpTasks.AsQueryable().OrderBy(st => st.Order).ToList();
            foreach (var startUpTask in startUpTasks)
                startUpTask.Execute();
        }

        private void InitializeContainer(ContainerConfigurer configurer, EventBroker broker, UnisConfig config)
        {
            var builder = new ContainerBuilder();

            _containerManager = new ContainerManager(builder.Build());
            configurer.Configure(this, _containerManager, broker, config);
        }

        /// <summary>
        /// Initialize components and plugins in the macaca environment.
        /// </summary>
        /// <param name="config">Config</param>
        public void Initialize(UnisConfig config)
        {
            //startup tasks
            if (!config.IgnoreStartupTasks)
            {
                RunStartupTasks();
            }
        }

        public T Resolve<T>() where T : class
        {
            return ContainerManager.Resolve<T>();
        }

        public T Resolve<T>(string key) where T : class
        {
            return ContainerManager.Resolve<T>(key);
        }

        public object Resolve(Type type)
        {
            return ContainerManager.Resolve(type);
        }

        public T[] ResolveAll<T>()
        {
            return ContainerManager.ResolveAll<T>();
        }

    }
}
